package cn.net.bhb.base.utils;

import java.lang.ref.WeakReference;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

/**
 * Created by zkt on 2018-8-13.
 * Description:
 */

public class FragmentUtil {
    static FragmentUtil fragmentUtil;
    private Fragment preFragment;
    static int fragmentContainerId;

    public static FragmentUtil getInstance(int containerId) {
        if (fragmentUtil == null) {
            fragmentUtil = new FragmentUtil();
            fragmentContainerId = containerId;
        }
        return fragmentUtil;
    }

    public void switchFragment(FragmentActivity activity, Fragment targetFragment) {
        WeakReference<FragmentActivity> weakReference = new WeakReference<>(activity);
        FragmentActivity weakActivity = weakReference.get();

        FragmentTransaction transaction = weakActivity.getSupportFragmentManager().beginTransaction();
        if (!targetFragment.isAdded()) {
            transaction.add(fragmentContainerId, targetFragment, targetFragment.getClass().getName());
            if (preFragment != null) {
                transaction.hide(preFragment);
            }
        } else {
            transaction.show(targetFragment)
                    .hide(preFragment);
        }
        preFragment = targetFragment;

        transaction.commitAllowingStateLoss();
    }
}
